import axios from "axios";
import { ref } from "vue";

axios.defaults.baseURL = "http://47.113.227.126:9998/prod-api";

const token = ref("eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQxMmUzMDFmLWFlNzEtNDM0YS1iM2ZmLTJmYzg1NWU3OTY1YiJ9._HtnuMcPg9FhlCT4sop-d8hzOIn5QosgLlfPyL4-cN_yJnE1rrfEKhbILZ-AJwyfXFRmwcDKDZAVg1yNhW1vKQ");

const id = ref("");

const guankaList = ref([
    "game1-part1",
    "game1-part2",
    "game1-part3",
    "game2-part1",
    "game2-part2",
    "game2-part3",
    "game2-part4",
    "game2-part5",
    "game3-part1",
    "game3-part2",
]);

//获取平台ID
const getPlatIdByToken = async () => {
    try {
        const res = await axios.get("/getInfo", {
            headers: {
                Authorization: token.value,
            },
        });
        id.value = res.data.user.userId;
        return id.value;
    } catch (error) {
        console.error("Error fetching data:", error);
        return null;
    }
}
//获取应用身份信息
const getAppIdByToken = async () => {
    try {
        const userId = await getPlatIdByToken();
        if (userId) {
            const res = await axios.get(`/zuixia/relationship/list?relatedUserId=${userId}`, {
                headers: {
                    Authorization: token.value,
                },
            }
            );
            return res.data.rows[0];
        }
        return null;
    } catch (error) {
        console.error("Error fetching relationship data:", error);
        return null;
    }
}
//拉取题库某关卡下的题目
//zuixia/bank/list?pageNum=1&pageSize=10&checkpoint=game1-part1
const getQuestionsByGuanka = async (guanka) => {
    // 索引大于等于0且小于关卡列表长度
    if (guanka < 0 || guanka >= guankaList.value.length) {
        console.error("Invalid guanka:", guanka);
        return null;
    }
    try {
        const res = await axios.get(`/zuixia/bank/list?pageNum=1&pageSize=1000&checkpoint=${guankaList.value[guanka]}`, {
            headers: {
                Authorization: token.value,
            }
        },);
        return res.data.rows;
    } catch (error) {
        console.error("Error fetching questions data:", error);
        return null;
    }
}

// 使用示例
// 获取本应用信息
// getAppIdByToken().then(data => console.log("App ID Data:", data));

//取出关卡list的最大下标
// console.log("Guanka List Max Index:", guankaList.value.length - 1);
// getQuestionsByGuanka(1).then(data => console.log("Questions Data:", data));

//生成随机地图 返回题号数组
const generateMap = async () => {
    const map = [];
    for (let index = 0; index < guankaList.value.length; index++) {
        const questions = await getQuestionsByGuanka(index);
        // console.log("Questions:", questions);
        if (questions) {
            var shuffledQuestions = questions.map(q => q.questionId).sort(() => Math.random() - 0.5);
            console.log("Shuffled Questions:", shuffledQuestions);
            // 遍历所有题目，取出题号
            shuffledQuestions.forEach(q => {
                // guankaList.value[index] 提取出game1-part1 的中的game 的1作为checkpoint 1， part中的1作为section 1
                // console.log("Guanka:", guankaList.value[index]);
                const checkpoint = guankaList.value[index].split("-")[0].slice(4);
                const section = guankaList.value[index].split("-")[1].slice(4);
                console.log("Checkpoint:", checkpoint);
                console.log("Section:", section);
                map.push(q);
            });

        }
    }
    return map;
};
const produceSomeBodyMarks = async (token) => {
    try {
        const data = await getAppIdByToken(token);
        const userId = data.userId;
        const name = data.name;
        const relatedUserId = data.relatedUserId;

        console.log("userId:", userId);
        console.log("name:", name);
        console.log("relatedUserId:", relatedUserId);

        for (let index = 0; index < guankaList.value.length; index++) {
            const questions = await getQuestionsByGuanka(index);
            if (questions) {
                var shuffledQuestions = questions.map(q => q.questionId).sort(() => Math.random() - 0.5);
                console.log("Shuffled Questions:", shuffledQuestions);

                let roundcount = 1;
                for (const q of shuffledQuestions) {
                    const checkpoint = guankaList.value[index].split("-")[0].slice(4);
                    const section = guankaList.value[index].split("-")[1].slice(4);
                    console.log("Checkpoint:", checkpoint);
                    console.log("Section:", section);
                    console.log("Round:", roundcount);
                    console.log("QuestionId:", q);

                    await axios.post("/zuixia/chuanguan", {
                        userId: userId,
                        checkpoint: checkpoint,
                        section: section,
                        round: roundcount,
                        questionId: q,
                    }, {
                        headers: {
                            Authorization: token,
                        },
                    }).then(res => {
                        console.log("ok", res.data);
                    }).catch(err => {
                        console.error("Error inserting the record:", err);
                    });

                    roundcount += 1;
                }
            }
        }
    } catch (error) {
        console.error("Error", error);
    }
};




const getSombodysMarks = async (token) => {
    try {
        const data = await getAppIdByToken(token);
        const userId = data.userId;
        if (!userId) {
            console.error("请重新登录", userId);
            return null;
        }
        const name = data.name;
        const relatedUserId = data.relatedUserId;

        console.log("userId:", userId);
        console.log("name:", name);
        console.log("relatedUserId:", relatedUserId);
        // 向 /zuixia/chuanguan/list?pageNum=1&pageSize=10&userId=1&periodDays=1&checkpoint=1&section=1&round=1&completionTime=2024-06-18&passDuration=1&questionId=1
        // 发送GET请求，获取最新进度
        const res = await axios.get(`/zuixia/chuanguan/list?pageNum=1&pageSize=10&userId=${userId}`, {
            headers: {
                Authorization: token,
            },
        }
        ).then(res => {
            //返回该用户所有的做题记录
            //用户最新记录，解析rows.recordId rows.questionId rows.currentAnswer
            let data = res.data.rows;

            // data根据recordId从大到小排序
            data.sort((a, b) => b.recordId - a.recordId);

            // data根据recordId排序
            data.sort((a, b) => a.recordId - b.recordId);

            console.log("用户全部记录", data);
            //遍历data，取出currentAnswer不为空的最小recordId和对应的索引号和questionId和currentAnswer
            let currentAnswer = "";
            let recordId = -1;
            let questionId = -1;
            let index = -1;
            for (let i = 0; i < data.length; i++) {
                if (data[i].currentAnswer) {
                    currentAnswer = data[i].currentAnswer;
                    recordId = data[i].recordId;
                    questionId = data[i].questionId;
                    index = i;
                    break;

                }else{
                    console.log(data[i].recordId);

                }
            }
            console.log("最新记录", data[index]);
            console.log("最新记录的currentAnswer", currentAnswer);
            console.log("最新记录的recordId", recordId);
            console.log("最新记录的questionId", questionId);
            console.log("最新记录的索引号", index);

            console.log("下一题的完整信息", data[index - 1]);
            console.log("下一题的questionId", data[index - 1].questionId);



        });
    }
    catch (error) {
        console.error("获取最新进度失败", error);
    }
}
Date.prototype.getWeek = function () {
    var date = new Date(this.getTime());
    date.setDate(date.getDate() + 4 - (date.getDay() || 7));
    var yearStart = new Date(date.getFullYear(), 0, 1);
    var weekNo = Math.ceil((((date - yearStart) / 86400000) + 1) / 7);
    
    return weekNo;
};
const qiandao = async (token) => {
    try {
        const data = await getAppIdByToken(token);
        const userId = data.userId;
        if (!userId) {
            console.error("请重新登录", userId);
            return null;
        }
        const name = data.name;
        const relatedUserId = data.relatedUserId;

        console.log("userId:", userId);
        console.log("name:", name);
        console.log("relatedUserId:", relatedUserId);
       //向/zuixia/qiandao/list?pageNum=1&pageSize=1000&userId=1 拉取最新签到记录
        const res = await axios.get(`/zuixia/qiandao/list?pageNum=1&pageSize=1000&userId=${userId}`, {
            headers: {
                Authorization: token,
            },
        }
        ).then(res => {
            console.log("所有签到记录", res.data.rows);
            // {
            //     "createBy": null,
            //     "createTime": null,
            //     "updateBy": null,
            //     "updateTime": null,
            //     "remark": null,
            //     "checkinId": 5,
            //     "userId": 1,
            //     "checkinTime": "2024-06-01",
            //     "currentCheckinDays": 1,
            //     "currentWeek": 1,
            //     "weeklyCheckinCount": 1
            // }
            //取出checkinId最大的一条记录
            let checkinId = 0;
            let currentCheckinDays = 0;
            let currentWeek = 0;
            let weeklyCheckinCount = 0;
            let checkinTime = "";
            let index = -1;
            for (let i = 0; i < res.data.rows.length; i++) {
                if (res.data.rows[i].checkinId > checkinId) {
                    checkinId = res.data.rows[i].checkinId;
                    currentCheckinDays = res.data.rows[i].currentCheckinDays;
                    currentWeek = res.data.rows[i].currentWeek;
                    weeklyCheckinCount = res.data.rows[i].weeklyCheckinCount;
                    checkinTime = res.data.rows[i].checkinTime;
                    index = i;
                }
            }
            console.log("最新签到记录", res.data.rows[index]);
            const today = new Date().toISOString().split('T')[0];
            if (checkinTime === today) {
                console.log("今天已经签到过了");
                return;
            }
            console.log(checkinTime+"签到成功，今天的签到时间是：" + today);
            //取出当前是今年的第几周
            let week = new Date().getWeek();
            console.log("当前是今年的第几周", week);
            if(week==currentWeek){
                weeklyCheckinCount=weeklyCheckinCount+1;
            }else{
                weeklyCheckinCount=1;
            }
            console.log("本周签到次数",weeklyCheckinCount);
            currentCheckinDays=currentCheckinDays+1;
            console.log("累计签到",currentCheckinDays);
            //向/zuixia/qiandao插入签到记录
            axios.post("/zuixia/qiandao", {
                userId: userId,
                checkinTime: today,
                currentCheckinDays: currentCheckinDays,
                currentWeek: week,
                weeklyCheckinCount: weeklyCheckinCount,
            }, {
                headers: {
                    Authorization: token,
                },
            }).then(res => {
                console.log("签到成功", res.data);
            }).catch(err => {
                console.error("签到失败", err);
            });
        });
    }
    catch (error) {
        console.error("签到失败", error);
    }
}


//功能都在这里
//拉取某人最新进度和下一题信息

// getSombodysMarks(token.value);



//生成某人闯关地图（同一用户使用前请联系我删除旧的数据）
produceSomeBodyMarks(token.value);


//插入签到记录

// qiandao(token.value);

// qiandao(token.value);



